/**
 * @author thangnd
 *
 */
package edu.dongthang.controller;
import com.google.ads.AdRequest;
import com.google.ads.AdView;

import java.util.ArrayList;
import edu.dongthang.screens.R;
import android.accounts.NetworkErrorException;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.Intent;
import android.content.SharedPreferences;
import android.net.wifi.WifiInfo;
import android.net.wifi.WifiManager;
import android.os.Bundle;
import android.view.View;
import android.content.DialogInterface;
import android.content.SharedPreferences.Editor;
import android.graphics.Color;
import android.widget.EditText;
import android.widget.TextView;

public class Touch extends Activity {
	private EditText ipField;
	private EditText portField;
	private AlertDialog alert;
	private AlertDialog network_alert;
	private boolean firstRun = true;
	SimpleGestureFilter detector;
	String iIPv4 = "";
	String test = "";
	int port = 5444;
	ArrayList<String> servers = new ArrayList<String>();
	public static final String PREFS_NAME = "MyFile";
	SharedPreferences pref_ip;
	Editor editor;
	AppDelegate appDel;
	String ip;
	private AdView adView;
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);

		pref_ip = getApplicationContext().getSharedPreferences(PREFS_NAME, 0);
		editor = pref_ip.edit();
		
		appDel = ((AppDelegate) getApplication());
		
		adView = (AdView) this.findViewById(R.id.adView1);
        adView.loadAd(new AdRequest()); 
		//ip = appDel.Scan();
		
		TextView tv_ip = (TextView)findViewById(R.id.TextView01);
		TextView tv_port = (TextView)findViewById(R.id.TextView02);
		tv_ip.setTextColor(Color.GRAY);
		tv_port.setTextColor(Color.GRAY);
		ipField = (EditText) findViewById(R.id.EditText01);
		portField = (EditText) findViewById(R.id.EditText02);
		// Button scan = (Button) findViewById(R.id.scan);

		String serverRunning = getResources()
				.getString(R.string.server_running);
		String deviceNotConnect = getResources().getString(
				R.string.device_not_connected);
		String ok = getResources().getString(R.string.ok);

		WifiManager wifiManager = (WifiManager) getSystemService(WIFI_SERVICE);
		WifiInfo wifiInfo = wifiManager.getConnectionInfo();

		int ipAddress = wifiInfo.getIpAddress(); // wifiManager.
		
		if(ip != null){
			iIPv4 = ip;
		}else {
			iIPv4 = String.format("%d.%d.%d.%d", (ipAddress & 0xff),
					(ipAddress >> 8 & 0xff), (ipAddress >> 16 & 0xff),
					(ipAddress >> 24 & 0xff));
		}
		
//		Toast.makeText(this, " SSID " + wifiInfo.getSSID() + " ip " + ip,
//				Toast.LENGTH_SHORT).show();

		ipField.setText(iIPv4);
		portField.setText("5444");

		alert = new AlertDialog.Builder(this).create();
		alert.setTitle(R.string.server_unavailable);
		alert.setMessage(serverRunning);
		alert.setIcon(R.drawable.warning_icon);
		alert.setButton(ok, new DialogInterface.OnClickListener() {
			@Override
			public void onClick(DialogInterface dialog, int which) {
				return;
			}
		});

		network_alert = new AlertDialog.Builder(this).create();
		network_alert.setTitle(R.string.Network_unreachable);
		network_alert.setMessage(deviceNotConnect);
		alert.setIcon(R.drawable.warning_icon);
		network_alert.setButton(ok, new DialogInterface.OnClickListener() {
			@Override
			public void onClick(DialogInterface dialog, int which) {
				return;
			}
		});
	}

	@Override
	public void onResume() throws NullPointerException {
		super.onResume();
		//kiem tra appDell la null thi hien hop thoai thong bao yeu cau ket noi server

		if (!appDel.connected && !firstRun) {
			alert.show();
			// hien thi ra popup la khong ket noi voi may chu
		}

		appDel.stopServer();
	}

	@Override
	public void onPause() {
		super.onPause();
		firstRun = false;
	}
	
	@Override
    public void onDestroy() {
      if (adView != null) {
        adView.destroy();
      }
      super.onDestroy();
    }

	public void clickHandler(View view) throws NullPointerException {
		//AppDelegate appDel = ((AppDelegate) getApplicationContext());
		appDel.mouse_sensitivity = Math.round(50 / 20) + 1;
		// neu chua co ket noi thi thuc hien ket noi
		if (!appDel.connected) {
			String serverIp;
			int serverPort;
			serverIp = ipField.getText().toString();
			serverPort = Integer.parseInt(portField.getText().toString());
			try {
				appDel.createClientThread(serverIp, serverPort);
			} catch (NetworkErrorException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}

		int x;
		for (x = 0; x < 4; x++) {// every quarter second for one second check if
									// the server is reachable view.getContext()
			if (appDel.connected) {
				Intent intent = new Intent(this, Controller.class);
				//intent.putExtra("app", (CharSequence)appDel);
				startActivity(intent);
				//appDel.receivNote();
				x = 6;
			}
			try {
				Thread.sleep(250);
			} catch (Exception e) {
			}
		}

		if (!appDel.connected)
			if (!appDel.network_reachable)
				network_alert.show();
			else
				alert.show();
	}

}
